package leetcode.linkedlist;

/**
 * 反转链表
 * 反转一个单链表。
 * <p>
 * 进阶:
 * 链表可以迭代或递归地反转。你能否两个都实现一遍？
 */
public class Solution3 {
    public ListNode reverseList(ListNode head) {
        ListNode orign = head;
        ListNode result = new ListNode(0);
        result.next = null;
        ListNode r = result;
        while (orign != null) {
            ListNode temp = new ListNode(orign.val);
            temp.next = r.next;
            r.next = temp;
            orign = orign.next;
        }
        return result.next;
    }


    public static void main(String[] args) {
        ListNode l1 = new ListNode(1);
        ListNode ll1 = new ListNode(2);
        ListNode lll1 = new ListNode(3);
        ListNode llll1 = new ListNode(4);
        l1.next = ll1;
        ll1.next = lll1;
        lll1.next = llll1;
        ListNode before = l1;
        while (before != null) {
            System.out.println(before.val);
            before = before.next;
        }
        System.out.println("after:");
        ListNode result = new Solution3().reverseList(l1);
        ListNode temp = result;
        while (temp != null) {
            System.out.println(temp.val);
            temp = temp.next;
        }
    }
}



